define(['moment'], function (moment) {
    return ['$rootScope', '$scope', '$filter', '$stateParams', 'config', 'MMWService', '$timeout',
        function ($rootScope, $scope, $filter, $stateParams, config, $MMWService, $timeout) {
            $scope.init = function(){
                $scope.settingList={
                    eqp_no:'',
                    current_feederlist_no:'',
                    next_feederlist_no:'',
                }
                $scope.info_list = [];
                $scope.printList = []; // 列印詳情
                $scope.mode = 'query';

                // $scope.info_list=[
                //     {
                //         eqp_no:'eqp_01',
                //         slot_no:'1-1',
                //         material_no:'m001',
                //         status:'0'
                //     },
                //     {
                //         eqp_no:'eqp_02',
                //         slot_no:'1-2',
                //         next_slot_no:'1-12',
                //         material_no:'w001',
                //         status:'1'
                //     },
                //     {
                //         eqp_no:'eqp_03',
                //         slot_no:'1-3',
                //         material_no:'z002',
                //         status:'2'
                //     },
                //     {
                //         eqp_no:'eqp_04',
                //         slot_no:'1-4',
                //         material_no:'z001',
                //         status:'3'
                //     }
                // ]
            };
            
            $scope.back = function(){
                if($scope.mode == 'print'){
                    $scope.mode = 'preview';
                    document.getElementById('kmi-pdf-panel').src = '';
                } else {
                    $scope.$root.hideMenu();
                    $scope.$root.changeProgram('home', true);
                }
            };

            $scope.loadPlotList = function(){
                $MMWService.showQueryListPNIG({
                    page_mode: 29,
                    pageRecord:50,
                    condition: [
                        {name:$filter('translate')('common.queryList.plot_no'), column_name:'lotno', query_mode:'2', value:$scope.condition.plot_no, merge_condition_model:'AND'}
                    ],
                    header: [
                        {label:$filter('translate')('common.queryList.plot_no'), code:'page_no'},
                        {label:$filter('translate')('common.queryList.wo_c'), code:'wono'},
                        {label:$filter('translate')('common.queryList.item_c'), code:'productno'},
                        {label:$filter('translate')('common.queryList.item_n'), code:'productname'},
                        {label:$filter('translate')('common.queryList.item_spec'), code:'itemspec'}
                    ],
                    setCondition:function(conditions){
                        conditions.push({column_name:'status', query_mode:$scope.condition.serial_type==='PCSNO'?1:0, value:'11', merge_condition_model:'AND' });
                        return conditions;
                    },
                    selectCode:$scope.condition.plot_no,
                    confirm : function(selectItem){
                        $scope.condition.plot_no = selectItem.page_no;
                    }
                });
            };

            $scope.loadEquip = function(){//設備編號開窗
                $scope.$root.showQueryList({
                    key:'eqp_no',
                    header : [
                        {label:$filter('translate')('SMT23.setting.op_no'), code:'eqp_no'}, //設備
                    ],
                    query: function(conditions, feedback){
                        $MMWService.sendToServer({
                            uri: 'ServicesSMT.Module_SMT.prd_mtl_eqp_info_get', // 不良品入庫=入庫單，報廢入庫=報廢單
                            content:{},
                            success: function (data) {
                                feedback(data.eqp_list);
                            }
                        });
                    },
                    // selectCode: $scope.settingList.area_no,
                    confirm: function(selectItem, dialog){
                        $scope.settingList.eqp_no = selectItem.eqp_no;
                        $scope.settingList.current_feederlist_no = selectItem.feederlist;
                        $scope.current_feederlist_no = selectItem.feederlist_no
                        $scope.current_feederlist_ver = selectItem.feederlist_ver
                        dialog.hide();
                    }
                });
            }

            $scope.loadNextFeederlist = function(){//下一產品料表
                $scope.$root.showQueryList({
                    key:'feederlist_no',
                    header : [
                        {label:$filter('translate')('SMT23.setting.next_product_list'), code:'feederlist_no'}, // 生產線編號
                    ],
                    query: function(conditions, feedback){
                        $MMWService.pageNumberInfoGet({
                            page_mode : 'smt_next_feederlist',
                            query_condition_info : []
                        }, function (response) {
                            if(response && response.length > 0){
                                feedback(response);
                            } else {
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            }
                        });
                    },
                    // selectCode: $scope.settingList.area_no,
                    confirm: function(selectItem, dialog){
                        $scope.settingList.next_feederlist_no = selectItem.feederlist_no;
                        dialog.hide();
                    }
                });
            }

            $scope.loadCurrentList = function(){//當前料表開窗
                $scope.$root.showQueryList({
                    key:'feederlist_no',
                    header : [
                        {label:$filter('translate')('SMT23.setting.op_product_list'), code:'feederlist_no'}, // 生產線編號
                    ],
                    query: function(conditions, feedback){
                        $MMWService.pageNumberInfoGet({
                            page_mode : 'smt_current_feederlist',
                            query_condition_info : []
                        }, function (response) {
                            if(response && response.length > 0){
                                feedback(response);
                            } else {
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            }
                        });
                    },
                    // selectCode: $scope.settingList.area_no,
                    confirm: function(selectItem, dialog){
                        $scope.settingList.current_feederlist_no = selectItem.feederlist_no;
                        dialog.hide();
                    }
                });
            }

            $scope.search = function(){
                let content = {
                    current_feederlist_no:$scope.current_feederlist_no,
                    current_feederlist_ver:$scope.current_feederlist_ver,
                    next_feederlist_no:$scope.settingList.next_feederlist_no,
                    eqp_no:$scope.settingList.eqp_no
                }
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.prd_mtl_analysis_info_get',
                    content,
                    success: function (data) {
                        $scope.mode = 'list';
                        $scope.info_list = data.analysis_list;
                    }
                });
            }

            $scope.end_print= function(){
                $MMWService.sendToServer({
                    uri : 'ServicesSMT.Module_SMT.prd_mtl_analysis_print',
                    content : {
                        eqp_no:$scope.settingList.eqp_no,
                        current_feederlist_no:$scope.current_feederlist_no,
                        current_feederlist_ver:$scope.current_feederlist_ver,
                        next_feederlist_no:$scope.settingList.next_feederlist_no,
                        file_name:"",
                    },
                    success : function(data){
                        // $scope.mode = 'list';
                        // $scope.show_history = false;
                        // $scope.itemList = data.details;

                    }
                });
                // printTag($scope.info_list,0);
            }

            function printTag(tags, index){
                if(tags && index < tags.length){
                    if(window.nodeRequire){
                        var exec = window.nodeRequire('child_process').exec;
                        $rootScope.showToast($filter('translate')('SMT19.msg.prpare_print', {index:index}));
                        exec(tags[index].commandline, function(error, stdout, stderr){
                            if(error){
                                $rootScope.showAlert($filter('translate')('E01.msg.cantprint'));
                            }
                            index = index +1;
                            printTag(tags, index);
                        });
                    }
                }
            };

            // 列印完成後，需把列印詳情回送給後台做記錄
            function printWiplogProcess(){
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_SN.print_wiplog_process',
                    content : {
                        printList: $scope.printList
                    },
                    success : function(){}
                });
            }

            var pdf_url;
            $scope.preview = function(){
                //20180605 modify by 李栋 for mantis#0047558
                $MMWService.sendToServer({
                    uri: 'ServicesSMT.Module_SMT.prd_mtl_analysis_print',
                    content : {
                        // course:($scope.show_history?'1':'0'),
                        // plot_detail : plot_detail
                        eqp_no:$scope.settingList.eqp_no,
                        current_feederlist_no:$scope.current_feederlist_no,
                        current_feederlist_ver:$scope.current_feederlist_ver,
                        next_feederlist_no:$scope.settingList.next_feederlist_no,
                        file_name:$filter('translate')('SMT23.title'),
                    },
                    success : function(data){
                        pdf_url = data.smt_pdf_get[0].url_pdf;
                        if(pdf_url.indexOf('http://') == -1){
                            pdf_url = 'http://'+config.server.ip+':'+config.server.port+ pdf_url;
                        }
                        if(config.setting.outsidePDF == 'Y'){
                            var fs = window.nodeRequire('fs'), RuncardPath;
                            try{
                                RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                            }catch(e){
                                RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                            }
                            RuncardPath += '\\www\\Runcard';
                            if(!fs.existsSync(RuncardPath)){
                                fs.mkdirSync(RuncardPath);
                            }
                            $scope.$root.downloadFile(pdf_url, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                                window.nodeRequire('electron').shell.openItem(dist_path);
                            });
                        } else {
                            showPDFViewer(pdf_url);
                        }
                    }
                });
            };

            function showPDFViewer(pdf_url){
                try{
                    window.nodeRequire('nw.gui').Window.open(pdf_url, {
                        title:'PDF Viewer',
                        show: false,
                        icon:'icon/icon.png',
                        focus:true
                    }, function(win) {
                        win.on('loaded', function(){
                            win.show();
                            win.print();
                        });
                    });
                } catch (e){
                    $scope.mode = 'print';
                    document.getElementById('kmi-pdf-panel').src = 'JSplugins/pdfjs/web/viewer.html?file='+pdf_url+'&openfile=false&viewbookmark=false&printfile=false&download=false#zoom=page-width';
                }
            }

            //M#53071: 調整列印的方式，解決列印模糊的問題
            $scope.print = function(){
                if(window.nodeRequire){
                    var sumatraPDF = window.nodeRequire('sumatra-pdf');
                    if(sumatraPDF){
                        var fs = window.nodeRequire('fs'), RuncardPath;
                        try{
                            RuncardPath = window.nodeRequire('electron').remote.app.getAppPath();
                        }catch(e){
                            RuncardPath = window.nodeRequire('path').dirname(process.execPath)+'\\package.nw';
                        }
                        RuncardPath += '\\www\\Runcard';
                        if(!fs.existsSync(RuncardPath)){
                            fs.mkdirSync(RuncardPath);
                        }
                        $scope.$root.downloadFile(pdf_url, RuncardPath+'\\RuncardPreview.pdf', function(dist_path){
                            $scope.$root.showLoading();
                            window.nodeRequire('sumatra-pdf').printWithSettings({
                                path:RuncardPath+'\\RuncardPreview.pdf',
                                success:function(){
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                },
                                error:function(error){
                                    // 20201104 modify by WeiTing for M#77013 - 不清楚為何在實際列印後，有列印成一張紙或輸出成 PDF檔案時，都會執行 error區域，所以目前 error區域也先當列印完成後，把列印詳情回送給後台做記錄。
                                    printWiplogProcess(); // 列印完成後，需把列印詳情回送給後台做記錄
                                    $scope.$root.hideLoading();
                                    $scope.$root.showToast($filter('translate')('common.msg.success'));
                                    //console.error(error);
                                }
                            });
                        });
                    } else {
                        window.frames['kmi-pdf-panel'].pdf_print();
                    }
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
                /*
                if(config.setting.printSetting){
                    $PrintSetting.init({
                        callback:function(settings){
                            window.frames['kmi-pdf-panel'].pdf_print(settings);
                        }
                    });
                } else {
                    window.frames['kmi-pdf-panel'].pdf_print();
                }
                */
            };

            $scope.download = function(){
                window.frames['kmi-pdf-panel'].pdf_download();
            };

            $scope.cancel = function(){
                $scope.mode = 'preview';
                document.getElementById('kmi-pdf-panel').src = '';
                $scope.printList = [];
            };

            // 列印詳情開窗查詢
            $scope.printInfoDialog = function(item){
                $mdDialog.dialog('module/moduleA/program/publicDialog/printInfoDialog.tmp.html',
                    function(dialog){
                        return {
                            printList: {
                                program: 'SMT23',
                                repair_order_no: item.plot_no,  // 維修單單號
                                print_user: '', // 列印人員
                                start_date: moment().subtract(3, 'days').format('YYYY-MM-DD'), // 開始日期
                                start_time: moment().subtract(3, 'days').format('HH:mm:ss'), // 開始時間
                                end_date: moment().endOf('day').format('YYYY-MM-DD'), // 結束日期
                                end_time: moment().endOf('day').format('HH:mm:ss'), // 結束時間
                                printDetailList: []
                            },
                            init: function(){ // 初始化
                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: '', merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: '', merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '1', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            back: function() {
                                dialog.hide();
                            },
                            search: function() { // 查詢
                                var start_dateTime = dialog.printList.start_date + ' ' + dialog.printList.start_time, // 開始日期 + 開始時間
                                    end_dateTime = dialog.printList.end_date + ' ' + dialog.printList.end_time; // 結束日期 + 結束時間

                                $MMWService.pageNumberInfoGet({
                                    page_mode : 'print_wiplot_info_get',
                                    query_condition_info : [
                                        {column_name: 'PRINTNO', query_mode:'2', value: '%' + dialog.printList.repair_order_no + '%', merge_condition_model:'AND'}, // 維修單單號
                                        {column_name: 'CREATOR', query_mode:'2', value: '%' + dialog.printList.print_user + '%', merge_condition_model:'AND'}, // 列印人員
                                        {column_name: 'CREATEDATE', query_mode:'4', value: start_dateTime, merge_condition_model:'AND'}, // 列印时间 - 開始
                                        {column_name: 'CREATEDATE', query_mode:'5', value: end_dateTime, merge_condition_model:'AND'}, // 列印时间 - 結束
                                        {column_name: 'PRINTTYPE', query_mode:'0', value: '1', merge_condition_model:'AND'} // 列印類型 - 1:批次流程卡; 2:系统出站标签; 3:末站标签打印; 4:外包单打印; 5:模具维修单打印;
                                    ]
                                }, function (response) {
                                    if(response && response.length > 0){
                                        dialog.printList.printDetailList = response;
                                    } else {
                                        dialog.printList.printDetailList = [];
                                        $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                                    }
                                });
                            },
                            changeStartDate: function() { // 更改開始日期
                                $datePicker.open(dialog.printList.start_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isBefore(dialog.printList.end_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.end_date))
                                        {
                                            dialog.printList.start_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else 
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column01')); // 開始日期不能大於結束日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            },
                            changeEndDate: function() { // 更改結束日期
                                $datePicker.open(dialog.printList.end_date,
                                    function(dialogType){
                                        if(moment(dialogType.datePacker.pickDate).isAfter(dialog.printList.start_date)
                                        || moment(dialogType.datePacker.pickDate).isSame(dialog.printList.start_date))
                                        {
                                            dialog.printList.end_date = moment(dialogType.datePacker.pickDate).format('YYYY-MM-DD');
                                            dialogType.hide();
                                        }  
                                        else
                                            $scope.$root.showAlert($filter('translate')('printInfoDialog.showAlert.column02')); // 結束日期不能小於開始日期！
                                    },
                                    function(dialogType){
                                        dialogType.hide();
                                    },{}
                                );
                            }
                        }
                    }
                );
            };
        }
    ];
});
